package com.dbappsecurity.network.api;

import com.dbappsecurity.network.Api;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;

/**
 * Created by Arirus on 2018/4/2.
 */

public class ApiHelper {
  private ApiHelper() {
  }

  public static MediaType JsonMediaType() {
    return MediaType.parse("application/json; charset=utf-8");
  }

  public static String rawUrl2Url(String url, Map<String, String> pathMap) {
    StringBuilder urlSB = new StringBuilder();
    urlSB.append(url);
    for (Map.Entry<String, String> entry : pathMap.entrySet()) {
      int start = urlSB.indexOf("{" + entry.getKey() + "}");
      if (start == -1) continue; //避免不匹配
      urlSB.replace(start, start + entry.getKey().length() + 2, entry.getValue());
    }
    //url里面还有path没有被替换
    if (urlSB.indexOf("/{") != -1 || urlSB.indexOf("}/") != -1 || urlSB.indexOf("}\"") != -1) {
      return null;
    }
    return urlSB.toString();
  }

  public static String rawUrl2Url(String url, List<String> pathList) {
    StringBuilder urlSB = new StringBuilder();
    urlSB.append(url);
    for (String path : pathList) {
      int start = urlSB.indexOf("{");
      int end = urlSB.indexOf("}");
      if (start == -1 || end == -1) continue; //避免不匹配
      urlSB.replace(start, end + 1, path);
    }

    //url里面还有path没有被替换
    if (urlSB.indexOf("/{") != -1 || urlSB.indexOf("}/") != -1 || urlSB.indexOf("}\"") != -1) {
      return null;
    }
    return urlSB.toString();
  }

  public static class DefaultErrorHandler implements Api.onError {
    @Override
    public void accept(Throwable throwable) throws Exception {

    }
  }

  public static class DefaultFinishHandler implements Api.onFinish {
    @Override
    public void run() throws Exception {

    }
  }

}
